package luhn

import (
	"regexp"
	"strconv"
	"strings"
)

const testVersion = 2

var regLuhn = regexp.MustCompile(`[0-9]`)
var regHasNotDigit = regexp.MustCompile(`\D`)

func Valid(input string) (valid bool) {
	if t, ok := ReversedStringToIntArray(input); ok {
		step := len(t) / 2
		var idx int
		for i := 1; i <= step; i++ {
			idx = i*2 - 1
			if t[idx]*2 > 9 {
				t[idx] = t[idx]*2 - 9
			} else {
				t[idx] = t[idx] * 2
			}
		}

		var sum int
		for i := 0; i < len(t); i++ {
			sum += t[i]
		}
		if sum%10 == 0 {
			valid = true
			return
		}
	}

	return
}

func ReversedStringToIntArray(input string) (output []int, ok bool) {
	input = strings.Replace(input, " ", "", -1)

	if len(input) <= 1 {
		return
	}

	if len(input) == 2 {
		input = "0" + input
	}

	if regHasNotDigit.FindString(input) != "" {
		return
	}

	t := regLuhn.FindAllString(input, -1)

	output = make([]int, len(t))
	for i := 0; i < len(t); i++ {
		r, _ := strconv.Atoi(t[i])
		output[i] = r
	}
	ok = true
	return
}
